"ui";

// 文件路径
const config_file_path = "/sdcard/auto_reader_config.txt";

var config = storages.create("auto_reader_config");
if (!config.contains("run_time_sp")) {
  // toastLog("使用默认配置");
  // 默认执行配置
  var default_conf = {
      exec_pattern:"1",
      run_time_sp: "9",
      read_count_sp:"4",
      exec_count:"1",
      begin_time_sp: "6",
      end_time_sp:"23",
      app_list:[
                {"appName":"微信","packageName":"com.tencent.mm","id":"cb1","checked":true},
                {"appName":"微鲤","packageName":"cn.weli.story","id":"cb2","checked":false}
              ]
  };
  // 储存默认配置到本地
  Object.keys(default_conf).forEach(function(key) {
    config.put(key, default_conf[key]);
  })
}


function draw_view() {
    ui.layout(
      <ScrollView>
        <vertical id="viewport">
        // viewport START     
          <frame>
            <appbar>
              <toolbar id="toolbar" title="运行配置" />
            </appbar>
          </frame>
          
          <vertical w="*" gravity="left" layout_gravity="left" margin="10">
            <text text="阅读模式：" textColor="#666666" textSize="14sp" />
            <radiogroup id="exec_pattern" orientation="horizontal" margin="0 10">
              <radio text="运行时长" checked="{{ '1'==config.get('exec_pattern')?true:false }}" />
              <radio text="阅读篇数" checked="{{ '2'==config.get('exec_pattern')?true:false }}" marginLeft="20" />
            </radiogroup>
          </vertical>

          <vertical visibility="{{ '1'==config.get('exec_pattern')?'visible':'gone' }}"  w="*" gravity="left" layout_gravity="left" margin="10">
            <text text="每个运行时长(分钟)：" textColor="#666666" textSize="14sp" />
            <spinner id="run_time_sp" entries="1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31|32|33|34|35|36|37|38|39|40|41|42|43|44|45|46|47|48|49|50|51|52|53|54|55|56|57|58|59|60" />
          </vertical>

          <vertical visibility="{{ '2'==config.get('exec_pattern')?'visible':'gone' }}" w="*" gravity="left" layout_gravity="left" margin="10">
            <text text="阅读篇数(篇)：" textColor="#666666" textSize="14sp" />
            <spinner id="read_count_sp" entries="1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31|32|33|34|35|36|37|38|39|40|41|42|43|44|45|46|47|48|49|50|51|52|53|54|55|56|57|58|59|60" />
          </vertical>

          <vertical w="*" gravity="left" layout_gravity="left" margin="10">
            <text text="运行模式：" textColor="#666666" textSize="14sp" />
            <radiogroup id="exec_count" orientation="horizontal" margin="0 10">
              <radio text="时段运行" checked="{{ '1'==config.get('exec_count')?true:false }}" />
              <radio text="单次运行" checked="{{ '2'==config.get('exec_count')?true:false }}" marginLeft="20" />
            </radiogroup>
          </vertical>

          <vertical visibility="{{ '1'==config.get('exec_count')?'visible':'gone' }}"  w="*" gravity="left" layout_gravity="left" margin="10">
            <text text="运行时段(时)：" textColor="#666666" textSize="14sp" />
            <horizontal w="*" gravity="center" layout_gravity="relative" margin="10">
              <spinner id="begin_time_sp" entries="0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21|22|23" />
              <text text="~" textColor="#666666" textSize="14sp" />
              <spinner id="end_time_sp" entries="0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21|22|23" />
            </horizontal>
          </vertical>

          <vertical w="*" gravity="left" layout_gravity="left" margin="10">
              <text textSize="16sp" margin="8">执行程序(多选)</text>
              <checkbox id="cb0" text="{{ config.get('app_list')[0]['appName'] }}" checked="{{ config.get('app_list')[0]['checked'] }}" marginLeft="16"/>
              <checkbox id="cb1" text="{{ config.get('app_list')[1]['appName'] }}" checked="{{ config.get('app_list')[1]['checked'] }}" marginLeft="16"/>
          </vertical>
         
          

          <horizontal w="*" gravity="center" layout_gravity="relative" margin="10">
              <button id="ok_btn" text="确定"/>
              <button id="cancel_btn" text="取消"/>
          </horizontal>

          <horizontal w="*" gravity="center" layout_gravity="relative" margin="10">
              <button id="clear_btn" text="清除本地储存"/>
          </horizontal>

        // viewport END  
        </vertical>
      </ScrollView>
    );

    // 更新本地配置同时重绘UI
    function update(target, new_val) {
      config.put(target, new_val);
    }

    // 格式化
    function format(val) {
      return val.toString();
    }

    // 运行模式
    ui.exec_pattern.setOnCheckedChangeListener(function(radioGroup, id) {
      // toastLog(id);
      let index = (id + 1) % radioGroup.getChildCount();
      //toast(radioGroup.getChildAt(index).getText());
      let exec_pattern = "1";
      if (ui.exec_pattern.getChildAt(0).checked) {
        exec_pattern = "1";
        update("exec_pattern", exec_pattern);
      } else {
        exec_pattern = "2";
        update("exec_pattern", exec_pattern);
      }
      // 运行时长(分钟)
      let run_time_sp = ui.run_time_sp.getSelectedItemPosition();
      update("run_time_sp",format(run_time_sp));
      // 阅读篇数(篇)
      let read_count_sp = ui.read_count_sp.getSelectedItemPosition();
      update("read_count_sp",format(read_count_sp));

      // 重绘UI
      draw_view();
      set_view_data();

    });

     // 运行次数
     ui.exec_count.setOnCheckedChangeListener(function(radioGroup, id) {
      // toastLog(id);
      let index = (id + 1) % radioGroup.getChildCount();
      //toast(radioGroup.getChildAt(index).getText());
      let exec_count = "1";
      if (ui.exec_count.getChildAt(0).checked) {
        exec_count = "1";
        update("exec_count", exec_count);
      } else {
        exec_count = "2";
        update("exec_count", exec_count);
      }
      
      let begin_time_sp = ui.run_time_sp.getSelectedItemPosition();
      update("begin_time_sp",format(begin_time_sp));
      
      let end_time_sp = ui.end_time_sp.getSelectedItemPosition();
      update("read_count_sp",format(end_time_sp));

      // 重绘UI
      draw_view();
      set_view_data();

    });

     // 执行程序 cb
     ui.cb0.on("check", (checked)=>{
      //  toastLog(ui.cb1.checked);
    });
     ui.cb1.on("check", (checked)=>{
      //  toastLog(ui.cb1.checked);
    });

    // 确定按钮
    ui.ok_btn.on("click",function(e){  
       /*
        let pos = ui.run_time_sp.getSelectedItemPosition();
        let item = ui.run_time_sp.getSelectedItem();
        toastLog(pos);
        toastLog(item);
        toastLog(ui.exec_pattern.getChildAt(0).checked)
      */
      //--------------动态更新存储----------------START
      // 运行模式
      let exec_pattern = "1";
      if(ui.exec_pattern.getChildAt(0).checked){
        exec_pattern = "1";
      }else{
        exec_pattern = "2";
      }
      update("exec_pattern",format(exec_pattern));

      let run_time_sp = ui.run_time_sp.getSelectedItemPosition();
      update("run_time_sp",format(run_time_sp));

      let read_count_sp = ui.read_count_sp.getSelectedItemPosition();
      update("read_count_sp",format(read_count_sp));
      
      // 运行次数
      let exec_count = "1";
      if(ui.exec_count.getChildAt(0).checked){
        exec_count = "1";
      }else{
        exec_count = "2";
      }
      update("exec_count",format(exec_count));

      let begin_time_sp = ui.begin_time_sp.getSelectedItemPosition();
      update("begin_time_sp",format(begin_time_sp));

      let end_time_sp = ui.end_time_sp.getSelectedItemPosition();
      update("end_time_sp",format(end_time_sp));
      
      // 执行程序(多选)
      var app_list = config.get('app_list');
      app_list[0]['checked'] = ui.cb0.checked;
      app_list[1]['checked'] = ui.cb1.checked;
      update("app_list",app_list);
      // toastLog(JSON.stringify(app_list));


      //--------------动态更新存储----------------END

      //--------------动态更新文件----------------START
      //文件路径
      var path = config_file_path;
      //要写入的文件内容
      let text = JSON.stringify(config);
      //以写入模式打开文件
      var file = open(path, "w");
      //写入文件
      file.write(text);
      //关闭文件
      file.close();
      //--------------动态更新文件----------------END

      engines.execScriptFile("./control.js");
      engines.myEngine().forceStop();

      //--------------关闭窗体----------------START
      // toastLog("已保存");
      // 关闭窗体
      activity.finish();
      //--------------关闭窗体----------------END
    });

    // 取消按钮
    ui.cancel_btn.on("click",function(e){
      // toastLog(e.getText());

       //--------------关闭窗体----------------START
       // 关闭窗体
       activity.finish();
       //--------------关闭窗体----------------END
    });

    // 清除本地储存
    ui.clear_btn.on("click", () => {
      confirm("确定要清除本地储存吗？")
        .then(ok => {
          if (ok) {
            storages.remove("auto_reader_config");
            files.remove(config_file_path)
            toastLog("清除成功");
          }
        });
    });

    //  // 更新所有配置
    //  ui.emitter.on("pause", () => {
    //    /*
    //     let pos = ui.run_time_sp.getSelectedItemPosition();
    //     let item = ui.run_time_sp.getSelectedItem();
    //     toastLog(pos);
    //     toastLog(item);
    //     toastLog(ui.exec_pattern.getChildAt(0).checked)
    //   */
    //   //--------------动态更新存储----------------START
    //   let exec_pattern = "1";
    //   if(ui.exec_pattern.getChildAt(0).checked){
    //     exec_pattern = "1";
    //   }else{
    //     exec_pattern = "2";
    //   }
    //   update("exec_pattern",format(exec_pattern));

    //   let run_time_sp = ui.run_time_sp.getSelectedItemPosition();
    //   update("run_time_sp",format(run_time_sp));

    //   let read_count_sp = ui.read_count_sp.getSelectedItemPosition();
    //   update("read_count_sp",format(read_count_sp));

    //   //--------------动态更新存储----------------END

    //   //--------------动态更新文件----------------START
    //   //文件路径
    //   var path = config_file_path;
    //   //要写入的文件内容
    //   let default_conf = {
    //     exec_pattern:exec_pattern,
    //     run_time_sp: format(run_time_sp),
    //     read_count_sp: format(read_count_sp)
    //   }
    //   let text = JSON.stringify(default_conf);
    //   //以写入模式打开文件
    //   var file = open(path, "w");
    //   //写入文件
    //   file.write(text);
    //   //关闭文件
    //   file.close();
    //   //--------------动态更新文件----------------END
    // });

}

function set_view_data(){

  let run_time_sp = config.get("run_time_sp");
  ui.run_time_sp.setSelection(run_time_sp);

  let read_count_sp = config.get("read_count_sp");
  ui.read_count_sp.setSelection(read_count_sp);

  let begin_time_sp = config.get("begin_time_sp");
  ui.begin_time_sp.setSelection(begin_time_sp);
  
  let end_time_sp = config.get("end_time_sp");
  ui.end_time_sp.setSelection(end_time_sp);

}


draw_view();
set_view_data();

